package com.tangw.management.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.sun.istack.internal.Nullable;
import com.tangw.management.model.User;
import com.tangw.management.repository.UserDao;
import com.tangw.management.service.UserService;

/**
 * 
 * @author TangW
 * @version 1.0
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Override
	public List<User> listUser(@Nullable Sort sort) {
		if (sort == null) {
			return (List<User>) userDao.findAll();
		} else {
			return (List<User>) userDao.findAll(sort);
		}
	}

	@Override
	public Long countUser() {
		return userDao.count();
	}

	@Override
	public User findUserById(Integer id) {
		Assert.notNull(id, "id不能为空");
		return userDao.findUserById(id);
	}

	@Override
	public User findUserByUsername(String username) {
		Assert.notNull(username, "username不能为空");
		return userDao.findByUsername(username);
	}

	@Override
	@Transactional
	public User createUser(User user) {
		Assert.notNull(user, "创建user不能为空");
		return userDao.save(user);
	}

	@Override
	@Transactional
	public int updateUser(User user) {
		Assert.notNull(user, "更新user不能为空");
		return userDao.updateUser(user.getRealname(), user.getAge(), user.getId());
	}

	@Override
	@Transactional
	public void deleteById(Integer id) {
		Assert.notNull(id, "删除id不能为空");
		userDao.delete(id);
	}

}
